import mongoose from 'mongoose';
import dotenv from 'dotenv';

dotenv.config();

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/zhunong_ai_platform';

// MongoDB连接配置
const mongooseOptions = {
  maxPoolSize: 20,
  serverSelectionTimeoutMS: 5000,
  socketTimeoutMS: 45000,
  bufferCommands: false,
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

export async function connectDatabase(): Promise<void> {
  try {
    await mongoose.connect(MONGODB_URI, mongooseOptions);
    console.log('✅ MongoDB连接成功');
    
    // 设置全局配置
    mongoose.set('debug', process.env.NODE_ENV === 'development');
    
    // 监听连接事件
    mongoose.connection.on('error', (error) => {
      console.error('❌ MongoDB连接错误:', error);
    });
    
    mongoose.connection.on('disconnected', () => {
      console.warn('⚠️ MongoDB连接断开');
    });
    
    mongoose.connection.on('reconnected', () => {
      console.log('🔄 MongoDB重新连接成功');
    });
    
  } catch (error) {
    console.error('❌ MongoDB连接失败:', error);
    throw error;
  }
}

export default mongoose; 